import { NextRequest, NextResponse } from 'next/server'
import { userQueries } from '@/lib/database-prisma'
import { verifyAccessToken } from '@/lib/casdoor'
import { PrismaClient } from '@/lib/generated/prisma'

const prisma = new PrismaClient()

export async function GET(request: NextRequest) {
  try {
    // 从cookies获取用户ID和访问令牌
    const userId = request.cookies.get('user_id')?.value
    const accessToken = request.cookies.get('access_token')?.value

    if (!userId || !accessToken) {
      return NextResponse.json({ error: '未登录' }, { status: 401 })
    }

    // 验证访问令牌
    const tokenResult = await verifyAccessToken(accessToken)
    if (!tokenResult.valid) {
      return NextResponse.json({ 
        error: tokenResult.error || '令牌无效',
        casdoorError: true
      }, { status: 401 })
    }

    // 获取当前用户
    const user = await userQueries.findById.get(parseInt(userId))
    if (!user) {
      return NextResponse.json({ error: '用户不存在' }, { status: 404 })
    }

    // 获取用户参与的所有非归档项目
    const userProjects = await prisma.userProjectLink.findMany({
      where: {
        userId: user.id,
        project: {
          isArchived: false
        }
      },
      include: {
        project: true
      }
    })

    const projectIds = userProjects.map((up: any) => up.project.id)

    if (projectIds.length === 0) {
      return NextResponse.json({ workload: [] })
    }

    // 获取所有状态不为"已完成"的todo
    const allTodos = await prisma.todoList.findMany({
      where: {
        status: {
          not: '已完成'
        },
        archived: false,
        todoProjectLinks: {
          some: {
            projectId: {
              in: projectIds
            }
          }
        }
      },
      include: {
        creator: true,
        assignee: true,
        todoProjectLinks: {
          include: {
            project: true
          }
        }
      }
    })

    // 定义高优先级标签
    const highPriorityTags = ['urgent', '紧急', 'high', '重要', 'critical', 'p0', 'p1']

    // 分离高优先级和普通优先级todo
    const highPriorityTodos = allTodos.filter((todo: any) => {
      if (!todo.tags) return false
      const todoTags = todo.tags.split(/[,\s]+/).map((tag: string) => tag.trim().toLowerCase())
      return highPriorityTags.some(tag => 
        todoTags.includes(tag.toLowerCase())
      )
    })

    const normalTodos = allTodos.filter((todo: any) => {
      if (!todo.tags) return true
      const todoTags = todo.tags.split(/[,\s]+/).map((tag: string) => tag.trim().toLowerCase())
      return !highPriorityTags.some(tag => 
        todoTags.includes(tag.toLowerCase())
      )
    })

    // 随机打乱数组
    const shuffleArray = (array: any[]) => {
      const shuffled = [...array]
      for (let i = shuffled.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        ;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
      }
      return shuffled
    }

    // 优先选择高优先级todo，然后补充普通优先级todo
    let selectedTodos = [...highPriorityTodos]
    if (selectedTodos.length < 6) {
      const remainingCount = 6 - selectedTodos.length
      const shuffledNormalTodos = shuffleArray(normalTodos)
      selectedTodos.push(...shuffledNormalTodos.slice(0, remainingCount))
    }

    // 限制最多6个
    selectedTodos = selectedTodos.slice(0, 6)

    // 格式化返回数据
    const workload = selectedTodos.map((todo: any) => ({
      id: todo.id,
      content: todo.content,
      status: todo.status,
      tags: todo.tags,
      created_by: todo.createdBy,
      creator_name: todo.creator.name,
      creator_color: todo.creator.color,
      assigned_to: todo.assignedTo,
      assignee_name: todo.assignee?.name || null,
      assignee_color: todo.assignee?.color || null,
      created_at: todo.createdAt,
      project_name: todo.todoProjectLinks[0]?.project.name || '未知项目'
    }))

    return NextResponse.json({ workload })
  } catch (error) {
    console.error('获取workload失败:', error)
    return NextResponse.json({ error: '获取workload失败' }, { status: 500 })
  }
} 